package com.cysion.study

import android.content.Intent
import android.location.Address
import android.location.Geocoder
import android.support.v4.app.Fragment
import android.text.TextUtils
import android.util.Log
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.cysion.other.color
import com.cysion.study.helper.FragmentListVals
import com.cysion.study.helper.UserCache
import com.cysion.study.helper.UserCache.cacheAddress
import com.cysion.study.helper.UserCache.lat
import com.cysion.study.helper.UserCache.lon
import com.cysion.study.helper.UserCache.radius
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.base.BaseFragmentAdapter
import com.cysion.study.ktbox.utils.ACache
import com.cysion.study.ktbox.utils.CLog
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.ktbox.utils.whiteTextTheme
import com.cysion.study.widget.LocationHelper
import com.cysion.study.widget.ShowToast
import com.cysion.targetfun._addOnPageChangeListener
import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException

/**
 * Created by chu on 2019-06-30.
 */
class MainActivity : BaseActivity() {

    private lateinit var mFragments: MutableList<Fragment>
    private lateinit var mTitles: MutableList<String>
    var lastClickTime = 0L


    override fun getLayoutId(): Int = R.layout.activity_main

    override fun initView() {
        UserCache.fromCache()
//        darkTextTheme(color(R.color.white))
        vpContent.offscreenPageLimit = 4
//        UserCache.lat = "104.067492"
//        UserCache.lon = "30.680626"
        // 初始化定位
//        initLocationClient()
        /*var latitude=36.091361
        var longitude=120.406274*/
        LocationHelper.getInstance(this)
        helper?.startClient()
        helper?.setListener {
            Log.e("百度定位", it.addrStr + it.latitude + "@@@" + it.longitude)
            UserCache.lat = it.latitude.toString()
            UserCache.lon = it.longitude.toString()
            UserCache.cacheAddress=it.address.toString()
            UserCache.city=it.city.toString()

        }
//        helper?.bdLocation?.city
    }
    lateinit var icons: IntArray
    internal var helper: LocationHelper? = LocationHelper.getInstance(this)
    var teacherType = "1"
    override fun initData() {
        super.initData()
//        var teacherType = /登录类型 1普通员工 2.家教
        teacherType = ACache.get(Box.context).getAsString("teacherType")
//        teacherType = "1"
        println("###教师类型=" + teacherType)
        if (teacherType == "1") {//普通教师首页fragment
            mFragments = FragmentListVals.getTeacherFragments()
            mTitles = FragmentListVals.getTitles()
        } else {//家教端页面
            mFragments = FragmentListVals.getPTeacherFragments()
            mTitles = FragmentListVals.getPTitles()
        }
        vpContent.adapter = BaseFragmentAdapter(this.supportFragmentManager, mFragments, mTitles)
        main_tablayout.setupWithViewPager(vpContent)


//        val icons = IntArray(3)
        // var teacherType = "0"//登录类型 0.普通教师 1.家教
        updateTopTheme(0)
        if (teacherType == "1") {
            icons = FragmentListVals.getIcons()//普教
        } else if (teacherType == "2") {
            icons = FragmentListVals.getPIcons()//家教
        }
//        val icons = FragmentListVals.getIcons()
        for (i in 0 until main_tablayout.getTabCount()) {
            main_tablayout.getTabAt(i)!!.setIcon(icons[i])
            main_tablayout.getTabAt(i)!!.setCustomView(R.layout.tabmain_item)
        }


        vpContent._addOnPageChangeListener {
            _onPageSelected {
                updateTopTheme(it)
            }
        }
        if (isRequestLocError()) {
            //定位失败
//            initLocationClient()
            helper?.startClient()
        }
    }

    override fun onResume() {
        super.onResume()
        var resetlogin = ACache.get(Box.context).getAsString("resetlogin")
        //为1 说明 更换账号登录后 首页切到首页
        println("####主页onResume="+resetlogin)
        if (resetlogin == "1") {
            vpContent.currentItem=0
            ACache.get(Box.context).put("resetlogin", "0")//为1 说明 更换账号登录后 首页切到首页
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        println("####主页返回="+requestCode+resultCode)
        if (resultCode == 100) {
            vpContent.currentItem=0
        }
    }

    private fun updateTopTheme(it: Int) {
//        teacherType = "0"//登录类型 0.普通老师 1.家教
        println("####登录类型="+teacherType+"###it="+it)
        if (teacherType == "1") {
            whiteTextTheme(color(R.color.main_cl))
        } else {
            if (it == 0) {
                darkTextTheme(color(R.color.white))
            }else if (it == 1) {
                darkTextTheme(color(R.color.white))
            }else if (it == 2) {
                whiteTextTheme(color(R.color.main_cl))
            }
        }

    }

    private fun initLocationClient() {
        Log.i("开始定位", "定位初始化")
        val mLocationClient = LocationClient(this.applicationContext)
        val mMyLocationListener = MyLocationListener()
        val option = LocationClientOption()
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.locationMode = LocationClientOption.LocationMode.Hight_Accuracy
        // 可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        option.setCoorType("bd09ll")
        val span = 50000
        option.setScanSpan(0)// //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setNeedDeviceDirect(true)//是否需要手机方向
        option.setIsNeedAddress(true)//可选，设置是否需要地址信息，默认不需要
        option.setIsNeedLocationDescribe(true)//可选，设置是否需要地址描述
        //可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
//        option.setLocationNotify(true);
        //可选，默认false，设置是否开启Gps定位
        option.isOpenGps = true
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
//        option.setOpenAutoNotifyMode();
        //设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
//        option.setOpenAutoNotifyMode(span, 0, LocationClientOption.LOC_SENSITIVITY_LOW)
        mLocationClient.locOption = option
        mLocationClient.registerLocationListener(mMyLocationListener)
        mLocationClient.start()
    }

    inner class MyLocationListener : BDAbstractLocationListener() {

        override fun onConnectHotSpotMessage(s: String?, i: Int) {

        }

        override fun onReceiveLocation(location: BDLocation) {
            if ("4.9E-324" != location.latitude.toString()) {
                UserCache.lat = location.latitude.toString()
                lat = location.latitude.toString() + ""
            }
            if ("4.9E-324" != location.longitude.toString()) {
                UserCache.lon = location.longitude.toString()
                lon = location.longitude.toString() + ""
            }
            radius = location.radius
            //获取纬度信息
            val latitude = location.latitude
            //获取经度信息
            val longitude = location.longitude
            //获取定位精度，默认值为0.0f
            val radius = location.radius
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
            val coorType = location.coorType
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            val errorCode = location.locType
            var provinceName = ""
            var cityName = ""
            if (!TextUtils.isEmpty(location.province) && !TextUtils.isEmpty(location.city)) {
                if (location.province == location.city) {
                    //直辖市
                    provinceName = location.city.replace("市", "")
                    cityName = location.city.replace("市", "")
                } else {
                    //非直辖市
                    provinceName = location.province.replace("省", "")
                    cityName = location.city.replace("市", "")
                }
            }
            //            address = location.getAddrStr();//获取定位地址
            val sb = StringBuffer(256)
            sb.append("time : ")
            sb.append(location.time)
            sb.append("\nerror code : ")
            sb.append(location.locType)
            sb.append("\nlatitude : ")
            sb.append(location.latitude)
            sb.append("\nlontitude : ")
            sb.append(location.longitude)
            sb.append("\nradius : ")
            sb.append(location.radius)
            sb.append("\ncity : ")
            sb.append(location.city)
            if (location.locType == location.gpsCheckStatus) {
                sb.append("\nspeed : ")
                sb.append(location.speed)
                sb.append("\nsatellite : ")
                sb.append(location.satelliteNumber)
                sb.append("\ndirection : ")
                sb.append("\naddr : ")
                sb.append(location.addrStr)
                sb.append(location.direction)
            } else if (location.locType.toString() == location.networkLocationType) {
                sb.append("\naddr : ")
                sb.append(location.addrStr)
                sb.append("\noperationers : ")
                sb.append(location.operators)
            }
            if (TextUtils.isEmpty(location.city)) {
                cacheAddress = ""
            } else {
                cacheAddress =
                    location.province + location.city + location.district + location.street
            }
            if (isRequestLocError()) {
                //定位失败
//                action = BaiduLocReceiver.ACTION_BAIDU_LOC_FAILURE
                ShowToast("定位失败，请检查定位权限")
            } else {
                //定位成功
                Log.i("开始定位", "定位成功" + lon)
//                action = BaiduLocReceiver.ACTION_BAIDU_LOC_SUCCESS
            }

            if (TextUtils.isEmpty(cityName)) {
                var addList: List<Address>? = null
                val ge = Geocoder(applicationContext)
                try {
                    addList = ge.getFromLocation(location.latitude, location.longitude, 1)
                } catch (e: IOException) {
                    e.printStackTrace()
                }

                if (addList != null && addList.size > 0) {
                    for (i in addList.indices) {
                        val ad = addList[i]
                        cityName = ad.locality
                    }
                }
            }
            CLog.i("定位结果=$sb###定位城市=$cityName")
//            BroadcastManager.sendBaiduLocBroadcast(this@AppContext, action, lat, lon, provinceName, cityName, address)
        }
    }

    fun isRequestLocError(): Boolean {
        return "4.9E-324" == lat || "4.9E-324" == lon || TextUtils.isEmpty(lat) || TextUtils.isEmpty(
            lon
        )
    }




    override fun closeMvp() {
    }

    override fun onBackPressed() {
        if (System.currentTimeMillis() - lastClickTime >= 2000) {
            ShowToast("再点击一次即可退出")
            lastClickTime = System.currentTimeMillis()
            return
        }
        finish()
    }
}